package com.gitee.huxing.course.netty.server.adpater;

import com.alibaba.fastjson.JSONObject;
import com.gitee.huxing.course.netty.gateway.router.AbstractNettyRouter;
import com.gitee.huxing.course.netty.gateway.router.NettyRouter;
import com.gitee.huxing.course.netty.threadpool.ThreadPool;
import com.gitee.huxing.course.netty.vo.Response;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.servce.adpater
 * @ClassName: ServiceChannelHandlerAdpater
 * @Author: huxing
 * @DateTime: 2021-08-20 下午6:51
 */
@Slf4j
public class ServiceChannelHandlerAdpater extends ChannelInboundHandlerAdapter {

    /** 返回消息 **/
    private String message;

    public ServiceChannelHandlerAdpater(String message){
        this.message = message;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            FullHttpRequest request = (FullHttpRequest) msg;
            log.info("后台服务接收到请求消息: {}", request.content().toString(StandardCharsets.UTF_8));
            // 返回对象
            this.handle(request, ctx, JSONObject.toJSONString(this.fetch(request)));
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            // 最终释放对象空间
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    /**
     * @Description:
     * @Author: huxing
     * @param request
     * @param ctx
     * @param body
     * @Date: 2021/8/20 下午6:52
     **/
    private void handle(FullHttpRequest request, ChannelHandlerContext ctx, String body) {
        // 把返回丢掉线程池里面去处理
        ThreadPool.getInstance().getExecutor(1).execute(() -> {
            FullHttpResponse response = null;
            try {
                log.info("返回的记录信息: {}", body);
                response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                        Unpooled.wrappedBuffer(body.getBytes(StandardCharsets.UTF_8)));
                // 获取请求时间
                String requestTime = request.headers().get("requestTime");
                if (StringUtils.isEmpty(requestTime)){
                    requestTime = LocalDateTime.now().toString();
                }
                response.headers().set("requestTime", requestTime);
                response.headers().set("Content-Type", "application/json");
                response.headers().setInt("Content-Length",
                        response.content().readableBytes());
            } catch (Exception ex){
                log.error("处理出错: " + ex.getMessage());
                response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
            } finally {
                if (request != null){
                    if(!HttpUtil.isKeepAlive(request)){
                        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                    } else {
                        response.headers().set(CONNECTION, KEEP_ALIVE);
                        ctx.write(response);
                    }
                }
                ctx.flush();
            }
        });
    }

    /**
     * @Description:  根据请求的url处理返回结果
     * @Author: huxing
     * @return com.gitee.huxing.course.netty.vo.Response
     * @Date: 2021/8/20 下午6:58
     **/
    private Response fetch(FullHttpRequest request){
        Response response = new Response();
        response.setUri(request.uri());
        response.setBody("请求的消息内容: " + request.content().toString(StandardCharsets.UTF_8));
        response.setMessage(message);
        return response;
    }
}

